package com.lin.consume;

import com.corundumstudio.socketio.SocketIONamespace;
import com.lin.common.constant.CustomerServiceConstant;
import com.lin.common.constant.SocketIoConstant;
import com.lin.common.utils.DistanceUtils;
import com.lin.dao.RangesMapper;
import com.lin.socketio.dto.Encounter;
import com.lin.socketio.dto.MessageBase;
import com.lin.po.Customer;
import com.lin.po.Ranges;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(RocketMqConstant.ENCOUNTER_TOPIC + CustomerServiceConstant.CONSUMER_HANDLER)
public class EncounterConsumer implements ConsumerHandler {

    @Value("${encounter.age.bracket}")
    private Integer ageBracket;
    @Autowired
    private RangesMapper rangesMapper;

    @Value("${cs.top.logintime.minute}")
    private Integer minute;

    @Value("${cs.encounter.distance}")
    private Integer distance;

    @Autowired
    private SocketIONamespace socketIOEncounter;

    @Override
    public void onMessage(MessageBase msg) {
        Encounter e = (Encounter) msg;
        /**
         *  TODO 性能考虑则需要从redis获取列表，但是redis中内容会比较多（没有过滤对方性别、年龄大小），多个消费同时获取非过滤的列表出来时，则会出现内存溢出情况；
         *  但是由于需要比对是经纬度，不能再数据库中对比，故需要先在数据库过滤部分条件（登录时间、性别、年龄）后，才进行经纬度对比；
         *  1、以游标的方式通过sql查询过滤部分条件（登录时间、性别、年龄）
         */
        Cursor<Ranges> cursor = rangesMapper.listTop10Encounter(e.getAge(), ageBracket, minute, e.getGender() == Customer.GENDER_FEMALE ? Customer.GENDER_MALE : Customer.GENDER_FEMALE);
        cursor.forEach(r -> {
            Double d = DistanceUtils.getDistance(e.getLongitude(), e.getLatitude(), r.getLongitude(), r.getLatitude());
            if (d < distance) {
                socketIOEncounter.getBroadcastOperations().sendEvent(SocketIoConstant.ENCOUNTER_EVENT_NAME, e);
            }
        });

    }
}
